<?php
error_reporting(E_ERROR);
class Admini_Managewaybill1Controller extends Uuch_ManageController {

    public function init() {
        parent::init();
//        $this->appendCss('/css/home/warehouse.css');
//        $this->appendCss('/admins/css/common.css');
        $this->appendCss('/admins/css/yundan.css');
        $this->appendScript('/admins/js/jquery/jquery-1.7.2.min.js')->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js')->appendScript('/js/uuch.js');
        $p = $this->getSafeParam("p");
        if ($this->_getParam('action') == 'billaccep' && $this->getSafeParam("id")) {
            $result = Application_Model_wayBillItem::load($this->getSafeParam("id"));
            if ($result->problem == Application_Model_wayBillItem::Problem_Appear) {
                $p = 1;
            }
        }
        if ($p == 1) {
            $this->view->type = 'billProblem';
            $this->view->stype = 0;
            $this->view->countbillout1 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_StayUser);
            $this->view->countbillout2 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_StayUuch);
            $this->view->countbillout12 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_ReturnCancel);
            $this->view->countbillout11 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_PartReturn);
            $this->view->countbillout121 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_ReturnCancel, Application_Model_ProblemWay::Schedule_ApplyFor);
            $this->view->countbillout122 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_ReturnCancel, Application_Model_ProblemWay::Schedule_ReturnRoute);
            $this->view->countbillout123 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_ReturnCancel, Application_Model_ProblemWay::Schedule_InChannel);
            $this->view->countbillout124 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_ReturnCancel, Application_Model_ProblemWay::Schedule_InUuch);
            $this->view->countbillout111 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_PartReturn, Application_Model_ProblemWay::Schedule_ApplyFor);
            $this->view->countbillout112 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_PartReturn, Application_Model_ProblemWay::Schedule_ReturnRoute);
            $this->view->countbillout114 = Application_Model_ProblemWay::getProblemScheduleByCount(Application_Model_ProblemWay::Problem_PartReturn, Application_Model_ProblemWay::Schedule_InUuch);
        } else {
            $this->view->type = 'waybill';
            $this->view->stype = 99;
            $this->view->countVisiting = Application_Model_VisitingServer::getCountByInteriorTime(Application_Model_VisitingServer::Interior_InStore, null, 1);  //上门取件待打包
            $this->view->countbillout1 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_Processing, null, null); //已付款待受理
            $this->view->countbillout2 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_Confrimed, null, null);  //已受理待选择渠道
            $this->view->countbillout3 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_Incoice, null, null);   //已选择渠道待拣货
            $this->view->countbillout4 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_Picking, null, null); //已拣货待打包
            $this->view->countbillout5 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_Pick, null, null);   //已打包待确认渠道
            $this->view->countbillout6 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_AffirmChannel, null, null); //已确认渠道待交运

            // $this->view->countbillout10 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_Outstorage, null, null); //已交运待上系统
            // $this->view->countbillout11 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_System, null, null);  //已上系统待转单
            // $this->view->countbillout12 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_Singleno, null, null);   //已出转单待运输
            // $this->view->countbillout13 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_Transportation, null, null); //已运输待完成

            $WayBillSearch = new Application_Model_Filter_WayBillSearch();
            $WayBillSearch->starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 90, date("Y")));
            $WayBillSearch->endtime   = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
            $WayBillSearch->status = 10;
            $billall = Application_Model_wayBillItem::getBillAll($WayBillSearch, 0, 99999);
            $this->view->countbillout10 = $billall['size'];
            $WayBillSearch->status = 11;
            $billall = Application_Model_wayBillItem::getBillAll($WayBillSearch, 0, 99999);
            $this->view->countbillout11 = $billall['size'];
            $WayBillSearch->status = 12;
            $billall = Application_Model_wayBillItem::getBillAll($WayBillSearch, 0, 99999);
            $this->view->countbillout12 = $billall['size'];
            $WayBillSearch->status = 13;
            $billall = Application_Model_wayBillItem::getBillAll($WayBillSearch, 0, 99999);
            $this->view->countbillout13 = $billall['size'];

            $this->view->countbillout20 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_PickError, null, null);  //拣货异常
            $this->view->countbillout21 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_OverSystem, null, null);  //上系统超期
            $this->view->countbillout22 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_Oversingleno, null, null);  //转单超期
            $this->view->countbillout23 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_OutTransportation, null, null);  //运输异常
            $this->view->countbillout24 = Application_Model_wayBillItem::getcountbill(Application_Model_wayBillItem::Interior_Overachieve, null, null);  //签收预警
            $this->view->countbillout = Application_Model_wayBillItem::getcountbill(null, 1, null);  //问题运单

            $this->view->countbillout31 = Application_Model_wayBillItem::getcountbill(null, null, 1);  //今日
        }
    }

    public function indexAction() {
        $pagesize = $this->getSafeParam('pagesize');
        if (!$pagesize) {
            $pagesize = 10;
        }
        $pageindex = $this->getSafeParam('start');
        if (!$pageindex) {
            $pageindex = 0;
        }
        $this->setTitle('运管管理');
        $quick = $this->getSafeParam('quick');
        $timescope = $this->getSafeParam('timescope');
        $starttime = $this->getSafeParam('starttime');
        $endtime = $this->getSafeParam('endtime');
        $invoice = $this->getSafeParam("invoice");
        $isinvoice = $this->getSafeParam("isinvoice");
        $channelid = $this->getSafeParam("channelid");
        $cityid = $this->getSafeParam("cityid");
        $startweight = $this->getSafeParam("startweight");
        $endweight = $this->getSafeParam("endweight");
        $startpayment = $this->getSafeParam("startpayment");
        $endpayment = $this->getSafeParam("endpayment");
        $startmoney = $this->getSafeParam("startmoney");
        $endmoney = $this->getSafeParam("endmoney");
        $agentid = $this->getSafeParam('agentid');
        $statusid = $this->getSafeParam('statusid');
        $stus = $this->getSafeParam('stus');
        $day = $this->getSafeParam("day");
        $problem = $this->getSafeParam("problem");
        $isAddform = $this->getSafeParam("isAddform");
        $stype = 99;
        $status = "";
        if ($stus != '') {
            $status = $stus;
            $stype = $status;
            $statusid = $stus;
        }
        if ($statusid === "" || $statusid === null) {
            
        } else {
            $status = $statusid;
            $stype = $status;
        }
        if ($problem == 1) {
            $stype = 25;
        }
        if ($day == 1) {
            $stype = 26;
        }
        if ($isinvoice == 1) {
            $stype = 88;
        }
        $strart = date("m") % 3 == 0 ? date("m") / 3 : ((int) (date("m") / 3) + 1);
        if ($timescope != null) {
            switch ($timescope) {
                case 'lastweek':
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 7 - 7, date("Y")));
                    break;
                case "week":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                case "month":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                case "lastmonth":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, cal_days_in_month(CAL_GREGORIAN, date("m") - 1, date("Y")), date("Y")));
                    break;
                case "quarter":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, ($strart - 1) * 3 + 1, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                case "lastquarter":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, ($strart - 1) * 3 - 2, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, ($strart - 1) * 3, cal_days_in_month(CAL_GREGORIAN, ($strart - 1) * 3, date("Y")), date("Y")));
                    break;
                case "year":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, 1, 1, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                case "lastyear":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, 1, 1, date("Y") - 1));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, 12, cal_days_in_month(CAL_GREGORIAN, 12, date("Y") - 1), date("Y") - 1));
                    break;
                case "day7":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 6, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                case "day30":
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 30, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
                default :
                    $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 90, date("Y")));
                    $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    break;
            }
        } else {
            if ($starttime == null && $endtime == "") {
                $starttime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 90, date("Y")));
                $endtime = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")));
            }
        }
        $WayBillSearch = new Application_Model_Filter_WayBillSearch();
        $WayBillSearch->quick = $quick;
        $WayBillSearch->agentid = $agentid;
        $WayBillSearch->expressId = $channelid;
        $WayBillSearch->starttime = $starttime;
        $WayBillSearch->endtime = $endtime;
        $WayBillSearch->status = $status;
        $WayBillSearch->problem = $problem;
        $WayBillSearch->invoice = $invoice;
        $WayBillSearch->day = $day;
        $WayBillSearch->cityid = $cityid;
        $WayBillSearch->startweight = $startweight;
        $WayBillSearch->endweight = $endweight;
        $WayBillSearch->startpayment = $startpayment;
        $WayBillSearch->endpayment = $endpayment;
        $WayBillSearch->startmoney = $startmoney;
        $WayBillSearch->endmoney = $endmoney;
        $WayBillSearch->isAddform = $isAddform;
        $WayBillSearch->isinvoice = $isinvoice;
        $billall = Application_Model_wayBillItem::getBillAll($WayBillSearch, $pagesize, $pageindex);

        $uid=array();
        foreach($billall['list'] as $item){
            $paypalBill=Application_Model_PayBill::getCardBill($item->userId,$item->id,Application_Model_PayBill::TYPE_WAYBILL);
            if($paypalBill){
                $datepid=strtotime($paypalBill[0]->dateCreated)+60*60*24;
                if($datepid > time()){
                    $uid[]=$item->userId;
                }
            }
        }
        $this->view->paypalBill=$uid;

        $this->view->arrsta = Application_Model_wayBillItem::getStatusEnum();
        $this->view->agentcomp = Application_Model_AgentCompany::getAgentAll();
        $this->view->expresscomp = Application_Model_Express::getAll();
        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $words[] = chr(65 + $i);
        }
        $this->view->words = $words;
        $this->view->arrstatus = Application_Model_wayBillItem::getInteriorAll();
        $billalllist = $billall['list'];
        $this->view->quick = $quick;
        $this->view->agentId = $agentid;
        $this->view->channelid = $channelid;
        $this->view->timescope = $timescope;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        $this->view->cityid = $cityid;
        $this->view->startweight = $startweight;
        $this->view->endweight = $endweight;
        $this->view->startpayment = $startpayment;
        $this->view->endpayment = $endpayment;
        $this->view->startmoney = $startmoney;
        $this->view->endmoney = $endmoney;
        $this->view->billall = $billall;
        $this->view->billlist = $billalllist;
        $this->view->pagesize = $pagesize;
        $this->view->invoice = $invoice;
        $this->view->status = $statusid;
        $this->view->isAddform = $isAddform;
        $this->view->stype = $stype;
        $this->view->stus = $stus;
        if ($this->_getParam("export") == "csv") {
            error_reporting(NULL);
            ini_set('display_errors', 'Off');
            header("content-Type:text/html; charset=gb2312");
            header("Content-Type: application/vnd.ms-execl");
            header("Content-Disposition: attachment; filename=国际运单统计.csv");
            header("Pragma: no-cache");
            header("Expires: 0");
            /* first line */
            echo iconv("UTF-8", "GB2312", "悠奇运单号,");
            echo iconv("UTF-8", "GB2312", "单号,");
            echo iconv("UTF-8", "GB2312", "收件人名,");
            echo iconv("UTF-8", "GB2312", "收件人地址,");
            echo iconv("UTF-8", "GB2312", "国家,");
            echo iconv("UTF-8", "GB2312", "邮编,");
            echo iconv("UTF-8", "GB2312", "电话,");
            echo iconv("UTF-8", "GB2312", "包裹重量,");
            echo iconv("UTF-8", "GB2312", "申报,");
            echo iconv("UTF-8", "GB2312", "渠道商,");
            echo iconv("UTF-8", "GB2312", "运送方式,");
            echo "\r\n";
            /* start of second line */
            if ($billalllist != '') {
                foreach ($billalllist as $key => $Item) {
                    echo iconv("UTF-8", "GB2312", $Item->billNo) . ",";
                    echo iconv("UTF-8", "GB2312", $Item->logistics) . ",";
                    echo iconv("UTF-8", "GB2312", $Item->consignee) . ",";
                    echo iconv("UTF-8", "GB2312", str_replace("\r\n", " ", str_replace(',', ' ', $Item->conAdd))) . ",";
                    echo iconv("UTF-8", "GB2312", str_replace(',', ' ', $Item->UserCity->ename)) . ",";
                    echo iconv("UTF-8", "GB2312", $Item->conPostCode) . ",";
                    echo iconv("UTF-8", "GB2312", $Item->conTel) . ",";
                    $firstWeight = Application_Model_WayWeight::getWeightByType($Item->id, Application_Model_WeightType::FirstWeight);
                    echo iconv("UTF-8", "GB2312", $firstWeight ? round($firstWeight->weight / 1000, 2) : "0") . "kg,";
                    echo iconv("UTF-8", "GB2312", $Item->getFeeByType(Application_Model_FeeType::ReprotValue) ? $Item->getFeeByType(Application_Model_FeeType::ReprotValue) : " ") . ",";
                    echo iconv("UTF-8", "GB2312", $Item->agentcompname ? $Item->agentcompname->name : " ") . ",";
                    echo iconv("UTF-8", "GB2312", $Item->channelname ? $Item->channelname->name : " ") . ",";
                    echo "\r\n";
                }
            }
            exit;
        }
    }

    public function queryAction() {
        $productName = $this->getSafeParam('productName');
        $username = $this->getSafeParam('username');
        $state = $this->getSafeParam('state');
        $starttime = $this->getSafeParam('starttime');
        $endtime = $this->getSafeParam('endtime');
        $pagesize = $this->getSafeParam('pagesize');
        $pageindex = $this->getSafeParam('pageindex');
        $item = new Application_Model_wayBillItem();
        $result = Application_Model_wayBillItem::test($productName, $username, $state, $starttime, $endtime);
        echo '{"count":' . $result['count'] . ',"items":' . json_encode($result['result']) . '}';
        exit;
    }

    public function pagerAction() {
        $productName = $this->getSafeParam('productName');
        $username = $this->getSafeParam('username');
        $state = $this->getSafeParam('state');
        $starttime = $this->getSafeParam('starttime');
        $endtime = $this->getSafeParam('endtime');
        $pagesize = $this->getSafeParam('pagesize');
        $pageindex = $this->getSafeParam('pageindex');
        $item = new Application_Model_wayBillItem();
        $result = $item->queryWaybill($productName, $username, $state, $starttime, $endtime, $pagesize, $pageindex);
        echo json_encode($result[1]);
        exit;
    }

    public function detailsAction() {
        $id = $this->getSafeParam('id');
        $item = new Application_Model_wayBillItem();
        $result = $item->queryDetails($id);
        echo json_encode($result);
        exit;
    }

    public function dditAction() {
        $id = $this->getSafeParam('id');
        $set = array(
            //'productName' => $this->getSafeParam('productName'),
            'shipType' => $this->getSafeParam('shipType'),
            'logistics' => $this->getSafeParam('logistics'),
            'weight' => $this->getSafeParam('weight'),
            'bagWeight' => $this->getSafeParam('bagWeight'),
            'discountFee' => $this->getSafeParam('discountFee'),
            'shipFee' => $this->getSafeParam('shipFee'),
            'serviceFee' => $this->getSafeParam('serviceFee'),
            'shipMoney' => $this->getSafeParam('shipMoney'),
            'status' => $this->getSafeParam('status'),
            'consignee' => $this->getSafeParam('consignee'),
            'conTel' => $this->getSafeParam('conTel'),
            'conPostCode' => $this->getSafeParam('conPostCode'),
            'conAdd' => $this->getSafeParam('conAdd'),
        );
        $item = new Application_Model_wayBillItem();
        $result = $item->queryDdit($id, $set);
        echo json_encode(true);
        exit;
    }

    public function delAction() {
        $idlist = $this->getSafeParam('idList');
        $item = new Application_Model_wayBillItem();
        $result = $item->queryDel($idlist);
        echo json_encode(true);
        exit;
    }

    public function accepAction() {
        $idlist = $this->getSafeParam('idList');
        $item = new Application_Model_wayBillItem();
        $result = $item->queryAccep($idlist);
        echo json_encode(true);
        exit;
    }

    public function logAction() {
        $id = $this->getSafeParam('id');
        $item = new Application_Model_wayBillItem();
        $result = $item->queryLog($id);
        echo json_encode($result);
        exit;
    }

    public function addLogAction() {
        $row = array(
            'logisticsNo' => $this->getSafeParam('logisticsNo'),
            'opDate' => $this->getSafeParam('opDate'),
            'opState' => $this->getSafeParam('opState'),
            'opRemark' => $this->getSafeParam('opRemark'),
            'opUser' => 1,
        );
        $item = new Application_Model_wayBillItem();
        $result = $item->queryAddlog($row);
        echo $result;
        exit;
    }

    public function editLogAction() {
        $id = $this->getSafeParam('id');
        $set = array(
            'opDate' => $this->getSafeParam('opDate'),
            'opState' => $this->getSafeParam('opState'),
            'opRemark' => $this->getSafeParam('opRemark'),
        );
        $item = new Application_Model_wayBillItem();
        $result = $item->queryEdit($id, $set);
        echo 1;
        exit;
    }

    /*
     * 查看运单详情
     */

    public function billaccepAction() {
        $id = $this->getSafeParam('id');
        $operate = $this->getSafeParam('operate');
        $this->view->ma = $this->getSafeParam("ma");
        $this->setTitle('运单详情');
        if ($operate == "subissue") {
            $billid = $this->getSafeParam('billid');
            $title = $this->getSafeParam('issuetitle');
            $content = $this->getSafeParam("issuecontent");
            $issuetype = $this->getSafeParam('issuetype');
            $userid = $this->getSafeParam('userid');
            $message = $this->getSafeParam('message');
            $mail = $this->getSafeParam('mail');
            $reissue = Application_Model_problem::byaddissue($billid, $title, $content, $issuetype, $userid, $message, $mail, Application_Model_problem::TYPE_BILL);
            if (!$reissue) {
                $this->view->ma = 2;
            } else {
                $this->view->ma = 1;
            }
            $id = $billid;
        }

        $billall = Application_Model_wayBillItem::load($id);

        $Waybill=Application_Model_PaypalRisk::getWaybill($billall->userId);

        $waypaybill=Application_Model_PayBill::getCardBill($billall->userId,$billall->id,Application_Model_PayBill::TYPE_WAYBILL);
        if($waypaybill){
            $datepid=strtotime($waypaybill[0]->dateCreated)+60*60*24;
            if($datepid > time()){
                $waypaybill=$waypaybill; 
            }else{
                $waypaybill=FALSE;
            }
        }

        $this->view->waypaybill=$waypaybill;
        

        $this->view->Waybill=$Waybill;

        if ($billall->interior >= Application_Model_wayBillItem::Interior_Transportation) {
            $shipcode = Application_Model_wayBillItem::byShipcode($billall->channer);
            $this->view->logisticslog = Application_Model_wayBillItem::expressUrl($shipcode->code, $billall->logistics);
        }
        $expressCostItem = array();
        $firstWeight = Application_Model_WayWeight::getWeightByType($billall->id, Application_Model_WeightType::FirstWeight);
        $firstvolumeWeight = Application_Model_WayWeight::getWeightByType($billall->id, Application_Model_WeightType::FirstVolume);
        if ($billall->interior == Application_Model_wayBillItem::Interior_Confrimed) {
            $expressCostItem = $billall->getExpressReportCost();
        } else if ($billall->interior == Application_Model_wayBillItem::Interior_Pick) {
            if ($billall->ExpressBy->isVolume == 1) {
                $getWeight = (($firstWeight->weight >= $firstvolumeWeight->weight) ? $firstWeight->weight : $firstvolumeWeight->weight) / 1000;
            } else {
                $getWeight = ($firstWeight->weight) / 1000;
            }

            $expressCostItem = Application_Model_wayBillItem::getChannelIdWeightByExpress($billall->expressId, $getWeight, $billall->state);
            $this->view->getWeight = $getWeight;
        }
        $billVaServerInfo = array('isNoLogo' => array('value' => $billall->isNoLogo, 'label' => '去吊牌'), 'isNoSkin' => array('value' => $billall->isNoSkin, 'label' => '去包装'),
            'isWooden' => array('value' => $billall->isWooden, 'label' => '打木架'), 'isCompress' => array('value' => $billall->isCompress, 'label' => '真空'),
            'FragileFee' => array('value' => $billall->getFeeByType(Application_Model_FeeType::FragileFee), 'label' => '防震'),
            'OperateFee' => array('value' => $billall->getFeeByType(Application_Model_FeeType::OperateFee), 'label' => '操作费'),
            'OversizedFee' => array('value' => $billall->getFeeByType(Application_Model_FeeType::OversizedFee), 'label' => '超大费'));

        $this->view->addPayMoney = Application_Model_RepayLink::getSumMoney($this->getSafeParam('id'), 3);  //补交款
        $this->view->referer = $this->getReferer();
        $this->view->billVaServerInfo = json_encode($billVaServerInfo);
        $this->view->expressCostItem = $expressCostItem;
        $this->view->firstWeight = $firstWeight;
        $this->view->firstvolumeWeight = $firstvolumeWeight;

        $this->view->liclog = Application_Model_logisticslogItem::getByNo($billall->id);
        $this->view->billall = $billall;
        $this->view->agentcomp = Application_Model_AgentCompany::getAgentAll();
        $this->view->storedetail = $billall->getItems();
        $this->view->invoicedetail = $billall->getBillNoInvoice();
        $this->view->issuedetail = Application_Model_problem::byissue($id, Application_Model_problem::TYPE_BILL);
        $this->view->problemWay = Application_Model_ProblemWay::getByTypeWayId($billall->id);
        $this->view->scheduledetail = Application_Model_ProblemSchedule::getTypeWayIdBySchedule($billall->id);
        $this->view->cityItem = Application_Model_city::load($billall->state);
        $this->view->arrsta = Application_Model_wayBillItem::getStatusEnum();
        $this->view->allshiptype = Application_Model_Express::getAll();
        $this->view->shiptype = Application_Model_Express::load($billall->shipType);
        $this->view->waybillRemarks = Application_Model_Remark::getObjectRemark($billall->id);
        $this->view->channel = Uuch_Util::select(Application_Model_ExpressChannel::getAll(), function($item) {
                    return array('id' => $item->Id, 'expressId' => $item->ExpressId, 'agentId' => $item->AgentCompanyId, 'name' => $item->Name);
                });
    }

    /**
     * 获取返回按钮的地址
     */
    private function getReferer() {
        $rf = $this->_getParam('_rf');
        if ($rf) {
            return $rf;
        }
        $rf = $_SERVER['HTTP_REFERER'];
        if ($rf && strpos($rf, 'index') > 0) {
            return $rf;
        }
        return '/admini/managewaybill/index';
    }

    /**
     * 物流跟踪
     */
    public function getexpressAction() {
        //$id = $this->getSafeParam('id');
        $id = 61839;
        $bill = Application_Model_wayBillItem::load($id);
        $no = $bill->Logistics;

        $content = '';
        $isUrl = 0;
        $express = $bill->getExpressChannelBy();
        $seen = Application_Model_WayLog::getByWayIdInteriorType($id, Application_Model_WayLog::OperateType_Seen);
        if ($express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI100JSON) {
            $item = new Uuch_Track_KuaiDiAPI($express->trackNo, $no);
            $content = $item->query();
            if ($content) {
                $bill->affirmtransportation();      //自动上网
            } else {
                $content = "暂时查不到消息 ";
                $content .= '<a target="_blank" href="' . sprintf($express->TrackUrl, $no) . '">点击链接查看' . $express->name . '物流情况(单号:' . $no . ')</a>';
            }
        } else if ($express->TrackType == Application_Model_Express::TRACK_TYPE_3TH) {
            if ($express->Name == "新加坡EMS") {
                $sg = new Uuch_Track_SpeedPostAPI();
                $result = $sg->query($no);
                var_dump($result);exit;
                if (is_array($result) && !empty($result)) {
                    $bill->affirmtransportation();            //自动上网
                    $content = '<table><tr><td>Date and Time</td><td>Location</td><td>Status</td><td>Reason</td></tr>';
                    foreach ($result as $item) {
                        $content .= "<tr><td>$item->dateTime</td><td>$item->location</td><td>$item->status</td><td>$item->reason</td></tr>";
                    }
                } else {
                    $content = "暂时查不到消息 ";
                }
            } else {
                $sg = new Uuch_Track_ComOneExpressAPI($no);
                $result = $sg->query();
                if (is_array($result) && !empty($result)) {
                    $bill->affirmtransportation();          //自动上网
                    $content = '<table><tr><td>Date</td><td>Time</td><td>Location</td><td>Status</td></tr>';
                    foreach ($result as $item) {
                        $content .= "<tr><td>$item->date</td><td>$item->time</td><td>$item->location</td><td>$item->status</td></tr>";
                    }
                    $content .= '</table>';
                } else {
                    $content = "暂时查不到消息 ";
                }
            }
            $content .= '<a target="_blank" href="' . sprintf($express->TrackUrl, $no) . '">点击链接查看' . $express->name . '物流情况(单号:' . $no . ')</a>';
        } else if ($express->TrackType == Application_Model_Express::TRACK_TYPE_LINK) {
            $item = new Uuch_Track_SingpostAPI(sprintf($express->TrackUrl, $no));
            $result = $item->query();
            if (is_array($result) && !empty($result)) {
                $bill->affirmtransportation();      //自动上网
                $content = '<table><tr><td>Date</td><td>Description</td></tr>';
                foreach ($result as $item) {
                    $content .= "<tr><td>$item->date</td><td>$item->description</td></tr>";
                }
                $content .= '</table>';
            } else {
                $content = "暂时查不到消息 ";
            }
            $content .= '<a target="_blank" href="' . sprintf($express->TrackUrl, $no) . '">点击链接前往' . $express->name . '官网查看物流情况(单号:' . $no . ')</a>';
        } else if ($express->TrackType == Application_Model_Express::TRACK_TYPE_WEB) {
            if ($express->trackNo == "hkpost") {
                $item = new Uuch_Track_HkpostAPI(sprintf($express->TrackUrl, $no));
                $result = $item->query();
                if ($result) {
                    $bill->affirmtransportation();      //自动上网
                    if (is_array($result) && !empty($result)) {
                        $content = '<table><tr><td>Date</td><td>Location</td><td>Content</td></tr>';
                        foreach ($result as $item) {
                            $content .= "<tr><td>$item->date</td><td>$item->location</td><td>$item->content</td></tr>";
                        }
                        $content .= '</table>';
                    } else {
                        $content = $result;
                    }
                } else {
                    $content = "暂时查不到消息 ";
                }
                $content .= '<a target="_blank" href="' . sprintf($express->TrackUrl, $no) . '">点击链接查看' . $express->name . '物流情况(单号:' . $no . ')</a>';
            } else if ($express->trackNo == "singpost") {
                $item = new Uuch_Track_SingpostAPI(sprintf($express->TrackUrl, $no));
                $result = $item->query();
                if (is_array($result) && !empty($result)) {
                    $bill->affirmtransportation();      //自动上网
                    $content = '<table><tr><td>Date</td><td>Description</td></tr>';
                    foreach ($result as $item) {
                        $content .= "<tr><td>$item->date</td><td>$item->description</td></tr>";
                    }
                    $content .= '</table>';
                } else {
                    $content = "暂时查不到消息 ";
                }

                $content .= '<a target="_blank" href="' . sprintf($express->TrackUrl, $no) . '">点击链接查看' . $express->name . '物流情况(单号:' . $no . ')</a>';
            }
        }
        if ($seen) {
            $this->json(array('content' => $content, 'isUrl' => $isUrl, 'seeDate' => $seen->DateCreated, 'operator' => $seen->Operator, 'type' => 1));
        } else {
            $this->json(array('content' => $content, 'isUrl' => $isUrl));
        }
    }

    /*
     * 受理
     */

    public function billhearAction() {
        $idlist = $this->getSafeParam('idlist');
        $payWeight = $this->getSafeParam("payWeight");
        $result = Application_Model_wayBillItem::getUpstatus($idlist, $payWeight);
        echo $result;
        exit;
    }

    /*
     * 生成转单号
     */

    public function singlenoAction() {
        $id = $this->getSafeParam('id');
        $this->view->billall = Application_Model_wayBillItem::load($id);
        $this->view->storedetail = Application_Model_StoreItem::getBywayId($id);
        if ($this->view->billall->status != Application_Model_wayBillItem::STATUS_Sended) {
            $this->view->message = 42;
        }
        $operate = $this->getSafeParam('operate');
        if ($operate == 'single') {
            $costMoney = $this->getSafeParam('costMoney');
            $agentno = $this->getSafeParam('agentno');
            $logistics = $this->getSafeParam('logistics');
            $billid = $this->getSafeParam('billid');
            if ($agentno == '' || $logistics == '' || $costMoney == '') {
                $this->view->message = 43;
            } else {
                $arrwhere['agentNo'] = $agentno;
                $arrwhere['logistics'] = $logistics;
                $arrwhere['costMoney'] = $costMoney;
                $result = Application_Model_wayBillItem::getUpBill($billid, $arrwhere);
                if (!$result) {
                    $this->view->message = 6;
                } else {
                    $this->view->message = 4;
                }
            }
        }
    }

    /*
     * 发货
     */

    public function shipmentsAction() {
        $id = $this->getSafeParam('id');
        $this->view->billall = Application_Model_wayBillItem::load($id);
        $this->view->storedetail = Application_Model_StoreItem::getBywayId($id);
        if ($this->view->billall->status != Application_Model_wayBillItem::STATUS_Confrimed) {
            $this->view->message = 52;
        }
        $this->view->agentcomp = Application_Model_AgentCompany::getAgentAll();
        $operate = $this->getSafeParam('operate');
        if ($operate == 'single') {
            $refundMoney = $this->getSafeParam('refundMoney');
            if ($refundMoney >= 0) {
                $arrup = array(
                    'lastWeight' => $this->getSafeParam('lastWeight'),
                    'volumeWeight' => $this->getSafeParam('volumeWeight'),
                    'lastMoney' => $this->getSafeParam('lastMoney'),
                    'costMoney' => $this->getSafeParam('costMoney'),
                    'agentId' => $this->getSafeParam('agentid'),
                    'channer' => $this->getSafeParam('channer'),
                    'logistics' => $this->getSafeParam('logistics'),
                    'refundMoney' => $this->getSafeParam('refundMoney'),
                    'isrefund' => $this->getSafeParam('isrefund'),
                    'status' => Application_Model_wayBillItem::STATUS_Sended,
                    'dateSend' => date("Y-m-d H:i:s"),
                );
                $billid = $this->getSafeParam('billid');
                $result = Application_Model_wayBillItem::shipments($billid, $arrup);
                if ($result) {
                    $this->view->message = 5;
                } else {
                    $this->view->message = 6;
                }
            } else {
                $this->view->message = 7;
            }
        }
    }

    /*
     * 运单取消
     */

    public function cancelAction() {
        $id = $this->getSafeParam('id');
        $result = Application_Model_wayBillItem::getcancel($id);
        echo $result;
        exit;
    }

    public function cultfeeAction() {
        $weight = $this->getSafeParam('weight');
        $weight = $weight * 1000;
        $wayId = $this->getSafeParam('wayId');
        $way = Application_Model_wayBillItem::load($wayId);
//        $billLog = Application_Model_WayLog::getByWayIdInteriorType($way->id, Application_Model_WayLog::Type_BillAffirmChannel);
//        $expressId = $way->ExpressId;     
////        
//        if ($billLog) {
//            $expressId = $billLog->DescriptionByChannel ? $billLog->DescriptionByChannel->expressId : $expressId;
//        }

        $expressId = $way->ExpressChannelBy->Id;
//        var_dump($expressId);
		if ($expressId != 37 && $way->shipType == 37 && $way->shipFeeconfig == 7117) {
			$expressId = 37;
		}
        $prices = Application_Model_ExpressPrice::getPricesByCity($way->state);
        $SortKey = 0;
        foreach ($prices as $item) {
            if ($item->expressId == $expressId) {
                $SortKey = $item->getMoneyByweight($weight);
                break;
            }
        }

        $money = $way->getFeeByType(Application_Model_FeeType::EstimateShipFee);
        if ($SortKey == 0) {
            $SortKey = $money;
        }

        $refundMoney = $money - $SortKey;
        /* 马年端午节活动开始 */
        if ($way->getFeeByType(Application_Model_FeeType::ActivityDiscount) == "0.95") {
            $refundMoney = $refundMoney * 0.95;
        } else if ($way->getFeeByType(Application_Model_FeeType::ActivityDiscount) == "0.9") {
            $refundMoney = $refundMoney * 0.9;
        }
        /* 马年端午节活动结束 */
        if($refundMoney<$way->discountFee){
    		if ($way->discountFee > 0 && $refundMoney > 0) {
    			$refundMoney = 0;
    		}
        }
        $this->json(array('shipMoney' => number_format($SortKey, 2, '.', ''), "refundMoney" => number_format($refundMoney, 2, '.', '')));
    }

    /**
     * 打印清单
     */
    public function printAction() {
        $id = $this->getSafeParam('id');
        $billall = Application_Model_wayBillItem::load($id);
        $this->view->billall = $billall;
        $remarks = Application_Model_Remark::getObjectRemark($id);
        $this->view->remarkObject = $remarks;
        $this->view->storedetail = $billall->getStoreItems();
    }

    /**
     * 打印發票
     */
    public function invoiceAction() {
        $id = $this->getSafeParam('id');
        $ma = $this->getSafeParam('ma');
        $this->view->ma = $ma;
        if ($this->getSafeParam('operate') == "subinvoice" || $this->getSafeParam('operate') == "subprin" || $this->getSafeParam('operate') == "subpre" || $this->getSafeParam('operate') == "local") {

            $billno = $this->getSafeParam('billid');
            $userid = $this->getSafeParam('userid');
            $arrre = array(
                "waybillno" => $this->getSafeParam('awn1'),
                "invoiceno" => $this->getSafeParam('inv1'),
                "orderdate" => $this->getSafeParam('od1'),
                "address" => $this->getSafeParam('rad1'),
                "zipcode" => $this->getSafeParam('zipcode'),
                "country" => $this->getSafeParam('country'),
                "attn" => $this->getSafeParam('ncp1'),
                "tel" => $this->getSafeParam('rp1'),
                "total" => $this->getSafeParam('ztotal'),
                "reason" => $this->getSafeParam('reason'),
                "weight" => $this->getSafeParam('weight'),
            );
            $arradd = array();
            $j = 0;
            $num = $this->getSafeParam('num');
            for ($i = 1; $i < ($num + 1); $i++) {
                if ($this->getSafeParam('inna' . $i) == "" && $this->getSafeParam('insu' . $i) == "" && $this->getSafeParam('inpr' . $i) == "" && $this->getSafeParam('inhs' . $i) == "" && $this->getSafeParam('into' . $i) == "" && $this->getSafeParam('did' . $i) == "") {
                    continue;
                } else {
                    $arradd[$j]['description'] = $this->getSafeParam('inna' . $i);
                    $arradd[$j]['num'] = $this->getSafeParam('insu' . $i);
                    $arradd[$j]['price'] = $this->getSafeParam('inpr' . $i);
                    $arradd[$j]['hscode'] = $this->getSafeParam('inhs' . $i);
                    $arradd[$j]['total'] = $this->getSafeParam('into' . $i);
                    $arradd[$j]['did'] = $this->getSafeParam('did' . $i);
                    $arradd[$j]['pkgs'] = $this->getSafeParam('pkgs' . $i);
                    $j++;
                }
            }
            if ($arrre != array() && $arradd != array()) {
                $result = Application_Model_invoice::addinvoice($billno, $userid, $arrre, $arradd);
                $this->view->ma = $this->getSafeParam('operate') == "subprin" ? 3 : ($this->getSafeParam('operate') == "subpre" ? 4 : ($this->getSafeParam('operate') == "local" ? 6 : 1));
            } else {
                $this->view->ma = 2;
            }
        }
        $billall = Application_Model_wayBillItem::load($id);
        $this->view->storedetail = $billall->getStoreItems();
        $this->view->invoiceall = Application_Model_invoice::bybillNo($billall->billNo);
        $this->view->invoicedetail = Application_Model_invoicedetail::bybillNo($billall->billNo);
        $this->view->billall = $billall;
    }

    /**
     * 打印运单
     */
    public function addbillAction() {
        $id = $this->getSafeParam('id');
        $billall = Application_Model_wayBillItem::load($id);
        $shipType = $this->getSafeParam("shipType");
        if ($this->isPost()) {
            $billall->addBillLog(Application_Model_WayLog::Type_ShipType, $shipType);
        }
        $invoiceItem = Application_Model_invoicedetail::bybillNo($billall->billNo);
        $this->view->shipItem = Application_Model_WayLog::getByWayIdInteriorType($id, Application_Model_WayLog::Type_ShipType);
        $this->view->invoicedetail = $invoiceItem;
        $this->view->storedetail = $billall->getItems();
        $this->view->invoice = Application_Model_invoice::bybillNo($billall->billNo);
        $this->view->billall = $billall;
    }

    /**
     * 打印地址标签
     */
    public function addformAction() {
        $id = $this->getSafeParam('id');
        $billall = Application_Model_wayBillItem::load($id);
        if ($this->getSafeParam("opAction") == "saveAddress") {
            $billall->Consignee = $this->getSafeParam("con1");
            $billall->ConTel = $this->getSafeParam("cte1");
            $billall->ConAdd = $this->getSafeParam("cad1");
            $billall->ConPostCode = $this->getSafeParam("cpc1");
            $billall->save();
            $billall = Application_Model_wayBillItem::load($id);
            $this->view->ma = 1;
        }
        $affirmAgent = Application_Model_WayLog::getByWayIdInteriorType($billall->id, Application_Model_WayLog::Type_BillAffirmAgent);
        $agentId = $affirmAgent ? $affirmAgent->description : $billall->agentId;
        $this->view->billall = $billall;
        $this->view->agentId = $agentId;
    }

    public function billbugAction() {
        $id = $this->getSafeParam('id');
        $billall = Application_Model_wayBillItem::load($id);
        $storedetail = Application_Model_StoreItem::getBywayId($id);
        $operate = $this->getSafeParam('operate');
        if ($operate == 'billbug') {
            $status = $this->getSafeParam('status');
            $remark = $this->getSafeParam('remark');
            $result = Application_Model_wayBillItem::billbug($id, $status, $remark);
            $this->view->bugma = $result;
        }
        $this->view->billall = $billall;
        $this->view->storedetail = $storedetail;
    }

    public function addlogisticsAction() {
        $wayid = $this->getSafeParam('wayid');
        $opdate = $this->getSafeParam('opdate');
        $opremark = $this->getSafeParam('opremark');
        $result = new Application_Model_logisticslogItem();
        $result->wayId = $wayid;
        $result->opDate = $opdate;
        $result->opRemark = $opremark;
        $result->opState = 0;
        $result->opUser = 1;
        $result->save();
        echo 1;
        exit();
    }

    public function dellogisticsAction() {
        $id = $this->getSafeParam('id');
        $result = Application_Model_logisticslogItem::dellic($id);
        echo $result;
        exit();
    }

    public function shipfeepxAction() {
//        $cityId = $this->getSafeParam('cityId');
        $word = $this->getSafeParam('word');
        $weight = $this->getSafeParam('weight');
        if ($weight == null || $weight == '')
            $weight = 0.5;
//        $city = Application_Model_city::load($cityId);
//        $word = $city->Word;
        $w0 = $this->get4pxAmount($word, $weight);
        $this->_helper->result = $w0;
        $this->_helper->layout->disableLayout();
    }

    public function get4pxAmount($word, $weight) {
        require_once(APPLICATION_PATH . '/../library/4px/OrderOnlineTools.php');
        $soap = new OrderOnlineTools();
        //运费试算
        $arrs = array(
            //货物类型(默认：P)(Length = 1)
            "cargoCode" => 'P',
            //目的国家二字代码，参照国家代码表(Length = 2)
            "countryCode" => $word,
            //产品代码,该属性不为空，只返回该产品计费结果，参照产品代码表(Length = 2)
            //"productCode" => array("A1","A6","E5"),
            //计费结果产品显示级别(默认：1)(Length = 1)
            "displayOrder" => '1',
            //邮编(Length <= 10)
            "postCode" => '518000',
            //起运地ID，参照起运地ID表(Length <= 4)
            "startShipmentId" => '10',
            //计费重量，单位(kg)(0 < Amount <= [3,3])
            "weight" => $weight,
            //高(0 < Amount <= [3,3])
            "height" => '2',
            //长(0 < Amount <= [3,3])
            "length" => '2',
            //宽(0 < Amount <= [3,3])
            "width" => '2'
        );
        $result = $soap->chargeCalculateService($arrs);

        $result = Uuch_Util::quickArraySort($result['calculateFee'], 'totalRmbAmount');
        return $result;
    }

    /**
     * 发票预览页面
     */
    public function previewAction() {
        $id = $this->getSafeParam('id');
        $billall = Application_Model_wayBillItem::load($id);
        $download = $this->getSafeParam("download");
        if ($download == 1) {
            header("Content-type: application/octet-stream");
            $filename = $billall->billNo . ".html";
            $ua = $_SERVER["HTTP_USER_AGENT"];
            if (preg_match("/MSIE/", $ua)) {
                header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
            } else if (preg_match("/Firefox/", $ua)) {
                header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $filename . '"');
            }
        }

        $this->view->storedetail = Application_Model_StoreItem::getBywayId($id);
        $this->view->invoiceall = Application_Model_invoice::bybillNo($billall->billNo);
        $this->view->invoicedetail = Application_Model_invoicedetail::bybillNo($billall->billNo);
        $this->view->billall = $billall;
        $this->view->download = $download;
        $this->_helper->layout->disableLayout();
        $this->view->ma = $this->getSafeParam('ma');
    }

    /**
     * 问题运单标记正常
     */
    public function editwaybillAction() {
        $id = $this->getSafeParam('id');
        $result = Application_Model_problem::byeditissue($id, Application_Model_problem::TYPE_BILL);
        echo $result;
        exit;
    }

    /**
     * 生成报表
     */
    public function statementAction() {
        $id = $this->getSafeParam('id');
        $billall = Application_Model_wayBillItem::load($id);
        $cityitem = Application_Model_city::load($billall->state);
        $invoicedetail = Application_Model_invoicedetail::bybillNo($billall->billNo);
        $cd = '';
        $dv = 0;
        if ($invoicedetail) {
            foreach ($invoicedetail as $value) {
                $cd.= $value->description . '、';
                $dv+= $value->total;
            }
        }
        header("content-Type:text/html; charset=gbk");
        header("Content-Type: application/vnd.ms-execl");
        header("Content-Disposition: attachment; filename=新加坡EMS" . date('Y-m-d') . ".cvs");
        header("Pragma: no-cache");
        header("Expires: 0");
        /* first line */
        echo "Tracking No." . "\t";
        echo "Ref No. (Optional)" . "\t";
        echo "Recipient Name" . "\t";
        echo "Recipient Address" . "\t";
        echo "Zip Code" . "\t";
        echo "Country Code" . "\t";
        echo "Country Name" . "\t";
        echo "Phone No" . "\t";
        echo "Content Description" . "\t";
        echo "Declared Value (USD)" . "\t";
        echo "Weight(KG)" . "\t";
        echo "\t\n";
        /* start of second line */
        echo $billall->agentNo . "\t";
        echo "\t";
        echo $billall->consignee . "\t";
        echo $billall->conAdd . "\t";
        echo $billall->conPostCode . "\t";
        echo $cityitem->word . "\t";
        echo $cityitem->ename . "\t";
        echo $billall->conTel . "\t";
        echo $cd . "\t";
        echo 'USD' . $dv . "\t";
        echo "\t\n";
        exit;
    }

    public function transAction() {
        $word = $this->getSafeParam('word');
        $rweight = $this->getSafeParam('rweight');
        $channelId = $this->getSafeParam('id');
        $express = Application_Model_Express::load($channelId);
        $costItem = $express->getReportCost($word, $rweight * 1000);
        $arrup = array();

        foreach (Uuch_Util::quickSort($costItem, 'price') as $costVal) {
            $arrup[] = array('agentName' => $costVal->AgentCompany->name, 'channelName' => $costVal->Channel->name, 'price' => $costVal->price, 'id' => $costVal->Id);
        }
        $this->json(array('data' => $arrup));
    }

    /**
     * 修改运单后台状态
     */
    public function editbillinteriorAction() {
        $id = $this->getSafeParam('id');
        $interior = $this->getSafeParam('interior');
        $billItem = Application_Model_wayBillItem::load($id);
        if ($billItem) {
            $result = $billItem->editBillInterior($interior);
            $this->json($result);
        } else {
            $this->json(1);
        }
    }

    /**
     * 修改运单前台状态
     */
    public function editbillstatusAction() {
        $id = $this->getSafeParam('id');
        $status = $this->getSafeParam('status');
        $billItem = Application_Model_wayBillItem::load($id);
        if ($billItem) {
            $result = $billItem->editBillStatus($status);
            $this->json($result);
        } else {
            $this->json(1);
        }
    }

    public function printexcelAction() {
        $id = $this->getSafeParam("id");
        $result = Uuch_PhpExcel::printexcel($id);
        exit;
    }

    public function pickingAction() {
        $id = $this->getSafeParam('id');
        $billall = Application_Model_wayBillItem::load($id);
        $this->view->billall = $billall;
        $this->view->storedetail = $billall->getStoreItems();
        $this->view->storetype = $billall->getItems();
        $this->_helper->layout->disableLayout();
    }

    public function upinteriorAction() {
        $id = $this->getSafeParam('id');
        $interior = $this->getSafeParam("status");
        $billall = Application_Model_wayBillItem::load($id);
        if ($billall) {
            $billall->interior = $interior;
            $billall->save();
            $billall->addBillLog($interior);
            echo 2;
            exit;
        } else {
            echo 1;
            exit;
        }
    }

    public function upshiptypeAction() {
        $id = $this->getSafeParam("billid");
        $shiptype = $this->getSafeParam("shiptype");
        $billall = Application_Model_wayBillItem::load($id);
        if ($billall) {
            $billall->shipType = $shiptype;
            $billall->save();
            echo 2;
            exit;
        } else {
            echo 1;
            exit;
        }
    }

    public function waybillcostAction() {
        $pagesize = 15;
        $pageindex = $this->getSafeParam('start');
        if (!$pageindex) {
            $pageindex = 0;
        }
        $name = $this->getSafeParam("name");
        $dateinbegin = $this->getSafeParam("dateinbegin");
        $dateinend = $this->getSafeParam("dateinend");
        $agentid = $this->getSafeParam('agentid');
        $res = Application_Model_Single::getFilter($name, $dateinbegin, $dateinend, $agentid, $pagesize, $pageindex);
        $this->view->dateinbegin = $dateinbegin;
        $this->view->dateinend = $dateinend;
        $this->view->name = $name;
        $this->view->agentid = $agentid;
        $this->view->agentcomp = Application_Model_AgentCompany::getAgentAll();
        $this->view->costlist = $res["list"];
        $this->view->costall = $res;
        $this->view->stype = 16;
    }

    public function innetworkAction() {
        $id = $this->getSafeParam("id");
        $billItem = Application_Model_wayBillItem::load($id);
        if ($billItem) {
            $billItem->interior = Application_Model_wayBillItem::Interior_Singleno;
            $billItem->save();
            $this->json(1);
        } else {
            $this->json(2);
        }
    }

    public function billexamineAction() {
        $id = $this->getSafeParam("id");
        $billItem = Application_Model_wayBillItem::load($id);
        if ($billItem) {
            if ($billItem->interior == Application_Model_wayBillItem::Interior_Confrimed) {
                $billItem->interior = Application_Model_wayBillItem::Interior_Incoice;
                $billItem->save();
                $this->json(1);
            } else {
                $this->json(2);
            }
        } else {
            $this->json(2);
        }
    }

    public function packstoreAction() {
        $id = $this->getSafeParam("id");
        $barcode = $this->getSafeParam("storeno");
        $billItem = Application_Model_wayBillItem::load($id);
        $result = $billItem->packstore($barcode);
        if ($result != 2) {
            $this->json(array('type' => $result));
        } else {
            $storeItem = Application_Model_StoreItem::surebybarcode($barcode);
            if ($storeItem) {
                $wayBill = Application_Model_wayBillItem::load($storeItem->wayId);
            }
            $interiorAll = Application_Model_wayBillItem::getInteriorAll();
            if ($storeItem) {
                if ($wayBill) {
                    $this->json(array("type" => 2, 'storeno' => $storeItem->userinfo->storeno, 'nikename' => $storeItem->userinfo->nikename, 'wayid' => $storeItem->wayId, 'interior' => $interiorAll[$wayBill->interior ? $wayBill->interior : 0] ? $interiorAll[$wayBill->interior] : "无状态"));
                } else {
                    $this->json(array("type" => 4));                          //无此包裹没有对应的运单号
                }
            } else {
                $this->json(array("type" => 3));                          //无此包裹的信息
            }
        }
    }

    public function affirmAction() {
        $idlist = $this->getSafeParam("idlist");
        $result = Application_Model_wayBillItem::getBillIdAffirm($idlist);
        $this->json($result);
    }

    public function isaddformAction() {
        $id = $this->getSafeParam("id");
        $result = Application_Model_wayBillItem::load($id);
        if ($result) {
            $result->isAddform = 1;
            $result->save();
            $this->json(2);
        } else {
            $this->json(1);
        }
    }

    public function isaddbillAction() {
        $id = $this->getSafeParam("id");
        $result = Application_Model_wayBillItem::load($id);
        if ($result) {
            Application_Model_Operate::addOperate(0, null, $result->billNo, "国际运单打印地址标签", $result->userId);
            $this->json(2);
        } else {
            $this->json(1);
        }
    }

    public function affirmshipchannelAction() {
        $id = $this->getSafeParam("id");
        $agentid = $this->getSafeParam("agentid");
        $channer = $this->getSafeParam("channer");
        $channel = $this->getSafeParam('channel');
        if ($channel) {
            $cost = Application_Model_ExpressCost::load($channel);
            $agentid = $cost->AgentCompanyId;
            $channer = $cost->ChannelId;
        }
        $billItem = Application_Model_wayBillItem::load($id);
        if (!$billItem) {
            $this->_redirect('/admini/managewaybill/billaccep/ma/4/id/' . $id . '?_rf=' . urlencode($this->_getParam('_rf')));
        }
        if (!$billItem->isInvoice) {
            $this->_redirect('/admini/managewaybill/billaccep/ma/6/id/' . $id . '?_rf=' . urlencode($this->_getParam('_rf')));
        }
        if ($billItem && $billItem->status == Application_Model_wayBillItem::STATUS_Confrimed && $billItem->interior == Application_Model_wayBillItem::Interior_Confrimed) {
            $billItem->interior = Application_Model_wayBillItem::Interior_Incoice;
            $billItem->agentId = $agentid;
            $billItem->channer = $channer;
            $billItem->save();
            Application_Model_Operate::addOperate(0, null, $billItem->billNo, "国际运单选择渠道", $billItem->userId);
            $billItem->addBillLog(Application_Model_wayBillItem::Interior_Incoice);
            $this->_redirect('/admini/managewaybill/billaccep/ma/3/id/' . $id . '?_rf=' . urlencode($this->_getParam('_rf')));
        } else {
            $this->_redirect('/admini/managewaybill/billaccep/ma/4/id/' . $id . '?_rf=' . urlencode($this->_getParam('_rf')));
        }
    }

    public function affirmpickAction() {
        $billid = $this->getSafeParam('id');
        $billItem = Application_Model_wayBillItem::load($billid);
        $result = $billItem->affirmPick();
        $this->json($result);
    }

    public function affirmpickingAction() {
        $billid = $this->getSafeParam('id');
        $billItem = Application_Model_wayBillItem::load($billid);
        $totalWeight = $this->getSafeParam("totalWeight");
        $totalVolume = $this->getSafeParam("totalVolume");
        /**
         * 添加渠道补交
         */
//        $ExpressChannelBy = $billItem->ExpressChannelBy;
//        $expressId = $ExpressChannelBy->Id;
//        $prices = Application_Model_ExpressPrice::getPricesByCity($billItem->state);
//        $SortKey = 0;
//        foreach ($prices as $item) {
//            if ($item->expressId == $expressId) {
//                if(1 == $ExpressChannelBy->isVolume){
//                    $SortKey = $item->getMoneyByweight($totalVolume);
//                }else{
//                    $SortKey = $item->getMoneyByweight($totalWeight);
//                }
//                
//                break;
//            }
//        }
//        $esShippingFee = $billItem->getFeeByType(Application_Model_FeeType::EstimateShipFee);
//        $lackFee = $esShippingFee - $SortKey;
//        if ($lackFee < 0) {
//            $account = Application_Model_UserAccount::load($billItem->userId);
//            if (0 >= $account->Money) {
//                $this->_redirect('/admini/managewaybill/billaccep/ma/6/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
//                return;
//            }
//            $account->decreaseMoney($lackFee, '快递渠道费用补交');
//            $user = Application_Model_User::load($billItem->userId);
//            $financeData = array(
//                'transaction_number' => '',
//                'trader' => 'backend-account-dr',
//                'customer_id' => $billItem->userId,
//                'member' => 'admin',
//                'amount' => $lackFee,
//                'currency' => 'CNY',
//                'customer_name' => $user->nikename,
//                'rate' => '1',
//                'rate_amount' => '0',
//                'period_start' => $account->Money,
//                'period_end' => $account->Money - $lackFee,
//                'business_type' => 'zltjbj-dr',
//                'order_sn' => $billItem->billNo
//            );
//            $this->_addFinance($account,$financeData);
//        }
        /**
         * 添加渠道补交
         */
        $isChange = $billItem->getChannelBy()->IsShipNo;
        $agentNo = $this->getSafeParam('agentNo');

        $logistics = (($isChange == 1 || $isChange == "1") ? $agentNo : "");
        $waynum = $this->getSafeParam("waynum");

        if ($waynum == 1) {
            $totalWeight = $this->getSafeParam("forecastWeight_1");
            $totalVolume = $this->getSafeParam("forecastvolumeWeight_1");
        }
//        var_dump($this->_getAllParams());exit;
        $splitArr = array();
        for ($index = 1; $index <= $waynum; $index++) {
            $splitArr[$index]["weight"] = $this->getSafeParam("forecastWeight_$index") * 1000;
            $splitArr[$index]["length"] = $this->getSafeParam("forecastlength_$index") ? $this->getSafeParam("forecastlength_$index") : 0;
            $splitArr[$index]["width"] = $this->getSafeParam("forecastwidth_$index") ? $this->getSafeParam("forecastwidth_$index") : 0;
            $splitArr[$index]["height"] = $this->getSafeParam("forecastheight_$index") ? $this->getSafeParam("forecastheight_$index") : 0;
        }
        $result = $billItem->affirmPickIng($agentNo, $logistics, $totalWeight, $totalVolume, $splitArr);

        if ($result == 1) {
            $this->_redirect('/admini/managewaybill/billaccep/ma/3/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        } else {
            $this->_redirect('/admini/managewaybill/billaccep/ma/4/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        }
    }

    public function affirmchannelAction() {
        $billid = $this->getSafeParam('id');
        $billItem = Application_Model_wayBillItem::load($billid);
        $result = $billItem->affirmChannel();
        $this->json($result);
    }

    public function affirmeditchannelAction() {
        $id = $this->getSafeParam("id");
        $agentid = $this->getSafeParam("agentid");
        $channer = $this->getSafeParam("channer");
        $billItem = Application_Model_wayBillItem::load($id);
        $channel = $this->getSafeParam('channel');
        if ($channel) {
            $cost = Application_Model_ExpressCost::load($channel);
            $agentid = $cost->AgentCompanyId;
            $channer = $cost->ChannelId;
        }
        $result = $billItem->affirmEditChannel($agentid, $channer);
        if ($result == 1) {
            $this->_redirect('/admini/managewaybill/billaccep/ma/3/id/' . $id . '?_rf=' . urlencode($this->_getParam('_rf')));
        } else {
            $this->_redirect('/admini/managewaybill/billaccep/ma/4/id/' . $id . '?_rf=' . urlencode($this->_getParam('_rf')));
        }
    }

    public function affirmoutAction() {
        $billid = $this->getSafeParam('id');
        $billItem = Application_Model_wayBillItem::load($billid);
        $result = $billItem->affirmOut();
        $this->json($result);
    }

    public function affirmsystemAction() {
        $billid = $this->getSafeParam('billid');
        $billItem = Application_Model_wayBillItem::load($billid);
        if ($billItem && ($billItem->interior == Application_Model_wayBillItem::Interior_Outstorage || $billItem->interior == Application_Model_wayBillItem::Interior_OverSystem)) {
            $arrup = array(
                'lastWeight' => $this->getSafeParam('lastWeight') * 1000,
                'lastVolumeWeight' => $this->getSafeParam('lastVolumeWeight') * 1000,
                'lwhth' => $this->getSafeParam('length') . '*' . $this->getSafeParam('width') . '*' . $this->getSafeParam('height'),
                'lastMoney' => $this->getSafeParam('lastMoney'),
                'refundMoney' => $this->getSafeParam('refundMoney'),
                'interior' => Application_Model_wayBillItem::Interior_System,
            );
            $account = Application_Model_UserAccount::load($billItem->userId);
            $periodStart = $account->Money;
            Application_Model_wayBillItem::shipments($billid, $arrup, "single");
            $lastWeight = $this->getSafeParam("lastWeight") * 1000;
            $lastvolumeWeight = $this->getSafeParam("lastVolumeWeight") * 1000;
            $billItem->editWeight(Application_Model_WeightType::LastWeight, $lastWeight);
            $billItem->editWeight(Application_Model_WeightType::LastVolume, $lastvolumeWeight);
            $billItem->addBillLog(Application_Model_wayBillItem::Interior_System);
            $user = Application_Model_User::load($billItem->userId);
            $amount = isset($arrup['refundMoney']) ? $arrup['refundMoney'] : 0;
            $periodEnd = $periodStart + $amount;
            $channelLog = Application_Model_WayLog::getByWayIdInteriorType($billItem->id, Application_Model_WayLog::Type_BillAffirmChannel);
            $channel = $billItem->channelname ? $billItem->channelname->name : "";
            if ($channelLog) {
                $channel = $channelLog->DescriptionByChannel->name;
            }
            $financeData = array(
                'transaction_number' => '',
                'trader' => 'account-number-dr',
                'customer_id' => $billItem->userId,
                'member' => 'admin',
                'amount' => $amount,
                'currency' => 'CNY',
                'customer_name' => $user->nikename,
                'rate' => '1',
                'rate_amount' => '0',
                'period_start' => $periodStart,
                'period_end' => $periodEnd,
                'business_type' => 'gjyftk',
                'order_sn' => $billItem->billNo,
                'attribute' => json_encode(array(
                    'channel' => $channel,
                    'orgin_ship_fee' => $billItem->getFeeByType(Application_Model_FeeType::EstimateShipFee),
                    'weight' => ($billItem->getWeightByType(Application_Model_WeightType::ProductWeight) + $billItem->getWeightByType(Application_Model_WeightType::BagWeight)) / 1000,
                    'volume' => $billItem->getWeightByType(Application_Model_WeightType::EstimateVolume) / 1000,
                    'new_weight' => $lastWeight / 1000,
                    'new_volume' => $lastvolumeWeight / 1000,
                    'real_ship_fee' => $arrup['lastMoney']
                )),
                'remark' => '',
                'created_at' => date('Y-m-d H:i:s')
            );
            $this->_addFinance($account, $financeData);
            $financeData['trader'] = 'backend-account-cr';
            $financeData['period_start'] = $periodEnd;
            $this->_addFinance($account, $financeData);

            $this->_redirect('/admini/managewaybill/billaccep/ma/3/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        } else {
            $this->_redirect('/admini/managewaybill/billaccep/ma/4/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        }
    }

    public function affirmsingleAction() {
        $billid = $this->getSafeParam('billid');
        $logistics = $this->getSafeParam("logistics");
        $billItem = Application_Model_wayBillItem::load($billid);
        if ($billItem && ($billItem->interior == Application_Model_wayBillItem::Interior_System || $billItem->interior == Application_Model_wayBillItem::Interior_Oversingleno)) {
            $billItem->logistics = $logistics;
            $billItem->interior = Application_Model_wayBillItem::Interior_Singleno;
            $billItem->save();
            $account = Application_Model_UserAccount::load($billItem->userId);
            $user = Application_Model_User::load($billItem->userId);
            $billItem->addBillLog(Application_Model_wayBillItem::Interior_Singleno);
            Application_Model_Operate::addOperate(0, null, $billItem->billNo, "国际运单更新转单号", $billItem->userId);
            $channelLog = Application_Model_WayLog::getByWayIdInteriorType($billItem->id, Application_Model_WayLog::Type_BillAffirmChannel);
            $agentLog = Application_Model_WayLog::getByWayIdInteriorType($billItem->id, Application_Model_WayLog::Type_BillAffirmAgent);
            $ccompany = $billItem->agentcompname ? $billItem->agentcompname->name : "";
            $channel = $billItem->channelname ? $billItem->channelname->name : "";
            if ($channelLog) {
                $channel = $channelLog->DescriptionByChannel->name;
            }
            if ($agentLog) {
                $ccompany = $agentLog->DescriptionByAgent->name;
            }
            $status = array(
                '1' => '出现问题',
                '2' => '问题解决',
                '3' => '运单取消'
            );
            $financeData = array(
                'transaction_number' => '',
                'trader' => 'backend-account-dr',
                'customer_id' => $billItem->userId,
                'member' => 'admin',
                'amount' => 0,
                'currency' => 'CNY',
                'customer_name' => $user->nikename,
                'rate' => '1',
                'rate_amount' => '0',
                'period_start' => $account->Money,
                'period_end' => $account->Money,
                'business_type' => 'qdydcbj',
                'order_sn' => $billItem->billNo,
                'attribute' => json_encode(array(
                    'waybill_status' => isset($status[$billItem->Problem]) ? $status[$billItem->Problem] : '正常',
                    'or_channel_company' => $ccompany,
                    'channel' => $channel,
                    'waybill_cost' => $billItem->lastMoney,
                    'channel_number' => $billItem->agentNo,
                    'channel_turn_number' => $logistics
                )),
                'remark' => $billItem->interiorRemark ? $billItem->interiorRemark : '',
                'created_at' => date('Y-m-d H:i:s')
            );

            $billRemark = Application_Model_Remark::getObjectRemark($billItem->id);
            if ($billRemark) {
                $remarkstr = '';
                foreach ($billRemark as $_remark) {
                    $remarkstr .= ' ' . $_remark->content;
                }
            }
            $financeData['remark'] = $remarkstr;
            $this->_addFinance($account, $financeData);
            $financeData['trader'] = 'account-number-cr';
            $this->_addFinance($account, $financeData);
            $this->_redirect('/admini/managewaybill/billaccep/ma/3/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        } else {
            $this->_redirect('/admini/managewaybill/billaccep/ma/4/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        }
    }

    public function affirmtransportationAction() {
        $billid = $this->getSafeParam("id");
        $billItem = Application_Model_wayBillItem::load($billid);
        if ($billItem && $billItem->interior == Application_Model_wayBillItem::Interior_Singleno || $billItem->interior == Application_Model_wayBillItem::Interior_OutTransportation) {
            $billItem->interior = Application_Model_wayBillItem::Interior_Transportation;
            $billItem->save();
            $billItem->addBillLog(Application_Model_wayBillItem::Interior_Transportation);
            Application_Model_Operate::addOperate(0, null, $billItem->billNo, "国际运单设置已上网", $billItem->userId);
            $this->json(2);
        } else {
            $this->json(1);
        }
    }

    public function affirmachieveAction() {
        $billid = $this->getSafeParam("id");
        $billItem = Application_Model_wayBillItem::load($billid);
        if ($billItem && ($billItem->status == Application_Model_wayBillItem::STATUS_Sended || $billItem->status == Application_Model_wayBillItem::STATUS_Complated) && ($billItem->interior == Application_Model_wayBillItem::Interior_Transportation || $billItem->interior == Application_Model_wayBillItem::Interior_Overachieve)) {
            $billItem->ActivityConsumeExchangeScore();
            $billItem->interior = Application_Model_wayBillItem::Interior_Achieve;
            $billItem->status = Application_Model_wayBillItem::STATUS_Complated;
            $billItem->save();
            $billItem->addBillLog(Application_Model_wayBillItem::Interior_Achieve);
            Application_Model_Operate::addOperate(0, null, $billItem->billNo, "国际运单已签收", $billItem->userId);
            $this->json(2);
        } else {
            $this->json(1);
        }
    }

    public function affirmpickerrorAction() {
        $billid = $this->getSafeParam("id");
        $billItem = Application_Model_wayBillItem::load($billid);
        $result = $billItem->affirmPickError();
        $this->json($result);
    }

    public function affirmfindAction() {
        $billid = $this->getSafeParam("id");
        $storeid = $this->getSafeParam("storeid");
        $billItem = Application_Model_wayBillItem::affirmfind($billid, $storeid);
        $this->json($billItem);
    }

    public function affirmproblemAction() {
        $billid = $this->getSafeParam("id");
        $content = $this->getSafeParam("content");
        $isProblem = $this->getSafeParam("isProblem");
        $billItem = Application_Model_wayBillItem::load($billid);
        if ($billItem && $billItem->status != Application_Model_wayBillItem::STATUS_Complated && $billItem->status != Application_Model_wayBillItem::Interior_Cancel) {
            if ($content != "") {
				if ($this->getRequest()->getParam('repay', 0) == 1) {
					$type = Application_Model_PayBill::TYPE_WAYBILL;
					$status = Application_Model_RepayLink::STATUS_CREATED;
					$old = Application_Model_RepayLink::getByRelationIdTypeStatus($billid, $type, $status);
					if ($old) {
						$old->delete();	
					}		
                    $repayMoney = (float)$this->getRequest()->getParam('repaysum');
                    if($repayMoney<0){
                        echo '补交金额不能为负数';
                        exit;
                    }			
					$link = new Application_Model_RepayLink(array(
						'name' => '运单' . $billItem->BillNo . '补交款',
						'description' => '',
						'type' => $type,
						'link' => $billItem->BillNo,
						'relationId' => $billid,
						'repayMoney' => $repayMoney));
					$link->Status = $status;
					$link->DateCreated = date('Y-m-d H:i:s');
					$link->UserId = $billItem->UserId;
					$link->save();
					$content .= '<h3>同意补款请点击<a href="http://www.uuch.com/pay/index/index/type/9/id/' . $link->Id . '">立即补款</a></h3>';
				}
				
                if ($billItem->problem != Application_Model_wayBillItem::Problem_Cancel && $isProblem == 1) {
                    $billItem->status = Application_Model_wayBillItem::STATUS_ExpressBack;
                    $billItem->problem = Application_Model_wayBillItem::Problem_Appear;
                    $billItem->save();
                    $billItem->addProblem($content);
                }
                if ($isProblem == 0) {
                    $billItem->addMessage($content);
                }

                $this->_redirect('/admini/managewaybill/billaccep/ma/3/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
            } else {
                $this->_redirect('/admini/managewaybill/billaccep/ma/5/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
            }
        } else {
            $this->_redirect('/admini/managewaybill/billaccep/ma/4/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        }
    }

    public function affirmachieveproblemAction() {
        $billid = $this->getSafeParam("id");
        $billItem = Application_Model_wayBillItem::load($billid);
        if ($billItem && $billItem->status != Application_Model_wayBillItem::STATUS_Complated && $billItem->status != Application_Model_wayBillItem::Interior_Cancel) {
//            if($billItem->problem == 1){
            if ($billItem->interior == Application_Model_wayBillItem::Interior_Processing) {
                $billItem->status = Application_Model_wayBillItem::STATUS_Processing;
            } else if ($billItem->interior < Application_Model_wayBillItem::Interior_Outstorage) {
                $billItem->status = Application_Model_wayBillItem::STATUS_Confrimed;
            } else {
                $billItem->status = Application_Model_wayBillItem::STATUS_Sended;
            }
            $billItem->problem = Application_Model_wayBillItem::Problem_Aolve;
            $billItem->save();
            Application_Model_Operate::addOperate(0, null, $billItem->billNo, "问题运单设置正常发货", $billItem->userId);
            $billItem->addProblemWay(Application_Model_ProblemWay::Problem_Allclear, Application_Model_ProblemWay::Schedule_Default);
            $billItem->addProblemSchedule("已和客户沟通，正常发货。", Application_Model_ProblemWay::Schedule_Default);
//            }
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    public function outstorageAction() {
        $this->view->agentcomp = Application_Model_AgentCompany::getAgentAll();
    }

    public function affirmscheduleAction() {
        $billid = $this->getSafeParam("id");
        $schedule = $this->getSafeParam("schedule");
        $crdate = $this->getSafeParam("crdate");
        $billItem = Application_Model_wayBillItem::load($billid);
        if ($billItem && $billItem->status != Application_Model_wayBillItem::STATUS_Complated && $billItem->status != Application_Model_wayBillItem::Interior_Cancel) {
            $billItem->addProblemSchedule($schedule, null, $crdate);
            $this->_redirect('/admini/managewaybill/billaccep/ma/3/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        } else {
            $this->_redirect('/admini/managewaybill/billaccep/ma/4/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        }
    }

    public function affirmreturncancelAction() {
        $billid = $this->getSafeParam("id");
        $billItem = Application_Model_wayBillItem::load($billid);
        $result = $billItem->affirmProblemReturnCancel();
        $this->json($result);
    }

    public function affirmpartreturnAction() {
        $billid = $this->getSafeParam("id");
        $billItem = Application_Model_wayBillItem::load($billid);
        $result = $billItem->affirmProblemPartReturn();
        $this->json($result);
    }

    public function addinteriorremarkAction() {
        $billid = $this->getSafeParam("id");
        $interiorcontent = $this->getSafeParam("interiorcontent");
        $billItem = Application_Model_wayBillItem::load($billid);
//        if ($billItem && $interiorcontent != "") {
//            $billItem->interiorRemark = ($billItem->interiorRemark != "" ? $billItem->interiorRemark . "<br>" : "") . Uuch_Util::getUserNikeName() . "留言：" . $interiorcontent;
//
////            var_dump($billItem->interiorRemark);exit;
//            $billItem->save();
        if ($billItem) {
            $remarkModel = new Application_Model_Remark();
            $data = array(
                'remarkType' => Application_Model_Remark::REMARKTYPE_INTERIOR,
                'content' => $interiorcontent,
                'operator' => Uuch_Util::getUserNikeName(),
                'objectId' => $billItem->id,
                'objectType' => Application_Model_Remark::OBJECT_WAYBILL_TYPE,
                'createdAt' => date('Y-m-d H:i:s')
            );
            $remarkModel->setData($data)->save();
            $this->_redirect('/admini/managewaybill/billaccep/ma/3/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        } else {
            $this->_redirect('/admini/managewaybill/billaccep/ma/5/id/' . $billid . '?_rf=' . urlencode($this->_getParam('_rf')));
        }
    }

    public function deleteremarkAction() {
        $id = $this->getSafeParam('id');
        if (!$id) {
            $this->json(2);
            return;
        }
        $remarkModel = new Application_Model_Remark();
        try {
            $remarkModel->Id = $id;
            $remarkModel->delete();
            $this->json(1);
        } catch (Exception $ex) {
            $this->json($ex->getMessage());
        }
    }

    public function indexremarkAction() {
        $billId = $this->getSafeParam("wayId");
//        $billItem = Application_Model_wayBillItem::load($billId);
        $remarks = Application_Model_Remark::getObjectRemark($billId);
        $billItem = Application_Model_wayBillItem::load($billId);
        $html = $billItem->InteriorRemark;
        if ($remarks) {
            $html .= '<table><tbody>';
            foreach ($remarks as $_remark) {
                $html .= '<tr><td>' . $_remark->operator . ' 在' . $_remark->createdAt . ' 留言</td>';
                $html .= '<td>' . $_remark->content . '</td>';
                $html .= '<td style="padding:0 0 0 38px;"><a href="javascript:void(0)" title="删除该备注" onclick="javascript:deleteWaybillRemark($(this),' . $_remark->id . ')">删除</a></td></tr>';
            }
            $html .= '</tbody></table>';
        }

        $this->json($html);
    }

    public function addindexremarkAction() {
        $billid = $this->getSafeParam("wayId");
        $interiorcontent = $this->getSafeParam("interiorcontent");
        $billItem = Application_Model_wayBillItem::load($billid);
        if ($billItem && $interiorcontent != "") {
//            $isRemark = $billItem->interiorRemark != "" ? 0 : 1;
//            $billItem->interiorRemark = ($billItem->interiorRemark != "" ? $billItem->interiorRemark . "<br>" : "") . Uuch_Util::getUserNikeName() . "留言：" . $interiorcontent;
//            $billItem->save();
            $isRemark = 1;
            if (Application_Model_Remark::getObjectRemark($billItem->id)) {
                $isRemark = 0;
            }
            $remarkModel = new Application_Model_Remark();
            $data = array(
                'remarkType' => Application_Model_Remark::REMARKTYPE_INTERIOR,
                'content' => $interiorcontent,
                'operator' => Uuch_Util::getUserNikeName(),
                'objectId' => $billItem->id,
                'objectType' => Application_Model_Remark::OBJECT_WAYBILL_TYPE,
                'createdAt' => date('Y-m-d H:i:s')
            );
            $remarkModel->setData($data)->save();
            $data['id'] = $remarkModel->id;
            $this->json(array("type" => 1, "indexRemark" => $data, "isRemark" => $isRemark));
        } else {
            $this->json(array("type" => 0));
        }
    }

    public function tabletforpickingAction() {
        $status = $this->getSafeParam('status');
        if ($status == 1) {
            $list = Application_Model_wayBillItem::toPick();
        } else if ($status == 2) {
            $list = Application_Model_WayBillItem::pickError();
        }
        $this->view->list = $list;
        $this->_helper->layout->disableLayout();
    }

    /**
     * 已查看物流信息
     */
    public function havetoseeAction() {
        $wayId = $this->getSafeParam("id");
        $wayLog = Application_Model_WayLog::getByWayIdInteriorType($wayId, Application_Model_WayLog::OperateType_Seen);
        $wayBill = Application_Model_wayBillItem::load($wayId);
        if (!$wayLog) {
            $wayLog = new Application_Model_WayLog();
        }
        $wayLog->WayId = $wayId;
        $wayLog->Description = $wayBill->BillNo . "的物流信息 已查看";
        $wayLog->IsShowFront = 0;
        $wayLog->DateCreated = date("Y-m-d H:i:s");
        $wayLog->Type = Application_Model_WayLog::Type_Bill;
        $wayLog->OperateType = Application_Model_WayLog::OperateType_Seen;
        $wayLog->Operator = Uuch_Util::getUserNikeName();
        $wayLog->save();
        $this->json(1);
    }

    public function batchtransportationAction() {
        $idlist = $this->getSafeParam("idlist");
        $arrid = explode(",", $idlist);
        for ($i = 0; $i < count($arrid); $i++) {
            $result = Application_Model_wayBillItem::load($arrid[$i]);
            if ($result != '') {
                if ($result->Interior == Application_Model_wayBillItem::Interior_Singleno || $result->Interior == Application_Model_wayBillItem::Interior_OutTransportation) {
                    $result->interior = Application_Model_wayBillItem::Interior_Transportation;
                    $result->save();
                    $result->addBillLog(Application_Model_wayBillItem::Interior_Transportation);
                    Application_Model_Operate::addOperate(0, null, $result->billNo, "国际运单设置已上网", $result->userId);
                }
            }
        }
        $this->json(1);
    }

    public function batchachieveAction() {
        $idlist = $this->getSafeParam("idlist");
        $arrid = explode(",", $idlist);
        for ($i = 0; $i < count($arrid); $i++) {
            $result = Application_Model_wayBillItem::load($arrid[$i]);
            if ($result != '') {
                if ($result->Interior == Application_Model_wayBillItem::Interior_Transportation || $result->Interior == Application_Model_wayBillItem::Interior_Overachieve) {
                    $result->ActivityConsumeExchangeScore();
                    $result->interior = Application_Model_wayBillItem::Interior_Achieve;
                    $result->status = Application_Model_wayBillItem::STATUS_Complated;
                    $result->save();
                    $result->addBillLog(Application_Model_wayBillItem::Interior_Achieve);
                    Application_Model_Operate::addOperate(0, null, $result->billNo, "国际运单设置已签收", $result->userId);
                }
            }
        }
        $this->json(1);
    }

    public function ship4pxAction() {
        $id = $this->getSafeParam("id");
        $channer = $this->getSafeParam("channer");
        $billItem = Application_Model_wayBillItem::load($id);
        if (!$billItem) {
            $this->json(array("type" => 0));
            return;
        }
        $result = Uuch_4pxAPI::CreatedBillByWayId($id, $channer);
        if ($result["type"] == 1) {
            $billItem->agentNo = $result["agentNo"];
            $billItem->save();
            Application_Model_Operate::addOperate(0, null, $billItem->billNo, "上传递四方获取渠道单号", $billItem->userId);
        }
        $this->json($result);
    }

    public function shipeubAction() {
        $id = $this->getSafeParam("id");
        $province = $this->getSafeParam("province");
        $city = $this->getSafeParam("city");
        $channer = $this->getSafeParam("channer");
        $wayItem = Application_Model_wayBillItem::load($id);
        if (!$wayItem) {
            $this->json(array("type" => 0));
        }
        if (!$wayItem->isInvoice) {
            $this->json(array("type" => 0, "message" => "请先制作好发票在上传"));
        }
        $result = Uuch_eub::createdEub($id, $province, $city);
        if ($result != "") {
            $wayItem->agentNo = $result;
            $wayItem->save();
            Application_Model_Operate::addOperate(0, null, $wayItem->billNo, "上传E邮宝获取渠道单号", $wayItem->userId);
            $this->json(array("type" => 1, "agentNo" => $result));
        } else {
            $this->json(array("type" => 0));
        }
    }

//    public function ship4pxAction() {
//        $id = $this->getSafeParam("id");
//        $agentNo = $this->getSafeParam("agentNo");
//        $forecastWeight = $this->getSafeParam("forecastWeight");
//        $forecastvolumeWeight = $this->getSafeParam("forecastvolumeWeight");
//        $result = Uuch_4pxAPI::CreatedBill($id, $agentNo, $forecastWeight, $forecastvolumeWeight);
//        $this->json($result);
//    }

    public function get4pxtableAction() {
        echo '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">';
        $agentNo = $this->getSafeParam("agentNo");
        $result = Uuch_4pxAPI::byAgentNo($agentNo);
        exit;
    }

//    public function shipeubAction() {
//        $id = $this->getSafeParam("id");
//        $forecastWeight = $this->getSafeParam("forecastWeight");
//        $province = $this->getSafeParam("province");
//        $city = $this->getSafeParam("city");
//        $result = Uuch_eub::createdEub($id, $forecastWeight, $province, $city);
//        if ($result != "") {
//            $this->json(array("type" => 1, "agentNo" => $result));
//        } else {
//            $this->json(array("type" => 0));
//        }
//    }

    public function eubpdfAction() {
        $id = $this->getSafeParam("id");
        $forecastWeight = $this->getSafeParam("forecastWeight");
        $agentNo = $this->getSafeParam("agentNo");
        Uuch_Tcpdf::printPDF("X4", $id, $forecastWeight, $agentNo);
        exit;
    }

    public function addsypropertyAction() {
        $id = $this->getSafeParam("id");
        $syproperty = $this->getSafeParam("syproperty");
        if ($syproperty !== "") {
            $wayItem = Application_Model_wayBillItem::load($id);
            if ($wayItem) {
                $wayItem->addBillLog(Application_Model_WayLog::Type_PropertySY, $syproperty);
                Application_Model_Operate::addOperate(0, null, $wayItem->billNo, "添加包裹属性：".$syproperty, $wayItem->userId);
                $this->json(1);
            } else {
                $this->json(0);
            }
        } else {
            $this->json(0);
        }
    }

    public function getshippingpriceAction() {
        $weight = $this->getSafeParam('weight');
        $weight = $weight * 1000;
        $wayId = $this->getSafeParam('wayId');
        $way = Application_Model_wayBillItem::load($wayId);
        $expressId = $way->ExpressChannelBy->Id;
        $prices = Application_Model_ExpressPrice::getPricesByCity($way->state);
        $SortKey = 0;
        foreach ($prices as $item) {
            if ($item->expressId == $expressId) {
                $SortKey = $item->getMoneyByweight($weight);
                break;
            }
        }
        $this->json(array('price' => $SortKey));
    }

    protected function _addFinance($account, $data) {
        require_once(APPLICATION_PATH . '/../library/finance/General.php');
        $api = new General($data['amount'], $account);
        $api->setFields($data);
        $api->addTransaction();
        return $this;
    }

    public function addfinanceAction() {
        require_once(APPLICATION_PATH . '/../library/finance/General.php');
        $id = $this->getSafeParam("id");
        $post = $this->getRequest()->getPost();
        $required = array('orgin_channel', 'orgin_ship_fee', 'weight', 'volume', 'amount', 'new_channel', 'new_ship_fee');
        $result = array();
        foreach ($required as $r) {
            if (!isset($post[$r]) || empty($post[$r])) {
                $result = array('code' => 'required', 'message' => $r . 'is required');
                break;
            }
        }
        if (empty($result)) {
            $wayBill = Application_Model_wayBillItem::load($id);
            $account = Application_Model_UserAccount::load($wayBill->userId);
            $money = trim($post['amount']);
            $beforeMoney = $account->Money;
            $user = Application_Model_User::load($wayBill->userId);
            $attributes = array(
                'or_channel_company' => $post['or_channel_company'],
                'orgin_channel' => $post['orgin_channel'],
                'orgin_ship_fee' => $post['orgin_ship_fee'],
                'weight' => $post['weight'],
                'volume' => $post['volume'],
                'new_channel_company' => $post['new_channel_company'],
                'new_ship_fee' => $post['new_ship_fee'],
                'new_channel' => $post['new_channel']
            );
            $periodEnd = $beforeMoney - $money;
            $data = array(
                'transaction_number' => '',
                'trader' => 'account-number-cr',
                'customer_id' => $wayBill->userId,
                'member' => 'admin',
                'amount' => $money,
                'currency' => 'CNY',
                'customer_name' => $user->nikename,
                'rate' => '1',
                'rate_amount' => '0',
                'period_start' => $beforeMoney,
                'period_end' => $periodEnd,
                'business_type' => 'qdbj',
                'order_sn' => $wayBill->billNo,
                'attribute' => \Zend_Json::encode($attributes),
                'remark' => '',
                'created_at' => date('Y-m-d H:i:s')
            );
        }

        try {
            $api = new General($post['amount'], $account);
            $api->setFields($data);
            $api->addTransaction();
            $api->setFields('trader', 'backend-account-dr')
                    ->setFields('period_start', $periodEnd)
                    ->setFields('period_end', $periodEnd);
            $api->addTransaction();
            $result = array('code' => 'success', 'message' => '');
        } catch (Exception $ex) {
            $result = array('code' => 'error', 'message' => $ex->getMessage());
        }

        $this->json($result);
    }

    public function zzfyfinanceAction() {
        require_once(APPLICATION_PATH . '/../library/finance/General.php');
        $id = $this->getSafeParam("id");
        $post = $this->getRequest()->getPost();
        $result = array();
        if (!isset($post['vaserver']) || !isset($post['amount'])) {
            $result = array('code' => 'required', 'message' => 'vaserver is required');
        }
        if (empty($result)) {
            $wayBill = Application_Model_wayBillItem::load($id);
            $account = Application_Model_UserAccount::load($wayBill->userId);
            $money = trim($post['amount']);
            $beforeMoney = $account->Money;
            $user = Application_Model_User::load($wayBill->userId);
            $attributes = array(
                'vaserver' => $post['vaserver']
            );
            $businessType = 'add' == $post['type'] ? 'zhengzhibujiao' : 'zhengzhituikuan';
            $customerTrader = 'zhengzhibujiao' == $businessType ? 'account-number-cr' : 'account-number-dr';
            $uuchTrader = 'zhengzhibujiao' == $businessType ? 'backend-account-dr' : 'backend-account-cr';
            $periodEnd = 'zhengzhibujiao' == $businessType ? $beforeMoney - $money : $beforeMoney + $money;
            $zzfyoptions = $this->getSafeParam("vaserver");
            $EstimateSum = $wayBill->getFeeByType(Application_Model_FeeType::EstimateSum);
            $types = array();
            if (FALSE !== strpos($zzfyoptions, 'isNoLogo')) {
                $wayBill->isNoLogo = 'add' == $post['type'] ? 1 : 0;
                $RemovalFee = 'add' == $post['type'] ? 20 : 0;
                $EstimateSum = 'add' == $post['type'] ? $EstimateSum + 20 : $EstimateSum - 20;
                $wayBill->addOrNewFee(Application_Model_FeeType::RemovalFee, $RemovalFee);
                array_push($types, '去吊牌');
            }
            if (FALSE !== strpos($zzfyoptions, 'isNoSkin')) {
                $wayBill->isNoSkin = 'add' == $post['type'] ? 1 : 0;
                array_push($types, '去包装');
            }
            if (FALSE !== strpos($zzfyoptions, 'isWooden')) {
                $wayBill->isWooden = 'add' == $post['type'] ? 1 : 0;
                $WoodenFee = 'add' == $post['type'] ? 50 : 0;
                $EstimateSum = 'add' == $post['type'] ? $EstimateSum + 50 : $EstimateSum - 50;
                $wayBill->addOrNewFee(Application_Model_FeeType::WoodenFee, $WoodenFee);
                array_push($types, '打木架');
            }
            if (FALSE !== strpos($zzfyoptions, 'isCompress')) {
                $wayBill->isCompress = 'add' == $post['type'] ? 1 : 0;
                $VacuumSeviceFee = 'add' == $post['type'] ? 20 : 0;
                $EstimateSum = 'add' == $post['type'] ? $EstimateSum + 20 : $EstimateSum - 20;
                $wayBill->addOrNewFee(Application_Model_FeeType::VacuumSeviceFee, $VacuumSeviceFee);
                array_push($types, '真空');
            }
            if (FALSE !== strpos($zzfyoptions, 'FragileFee')) {
                $productWeight = $wayBill->getWeightByType(Application_Model_WeightType::ProductWeight);
                $bagWeight = $wayBill->getWeightByType(Application_Model_WeightType::BagWeight);
                $fragileFee = 'add' == $post['type'] ? (($productWeight + $bagWeight) > 5000 ? 20 : 10) : 0;
                $EstimateSum = 'add' == $post['type'] ? $EstimateSum + $fragileFee : $EstimateSum - $fragileFee;
                $wayBill->addOrNewFee(Application_Model_FeeType::FragileFee, $fragileFee);
                array_push($types, '防震');
            }
            if (FALSE !== strpos($zzfyoptions, 'OperateFee')) {
                $EstimateSum = 'add' == $post['type'] ? $EstimateSum + $money : $EstimateSum - $money;
                $operateFee = $wayBill->getFeeByType(Application_Model_FeeType::OperateFee);
                $operateFee = 'add' == $post['type'] ? $operateFee + $money : $operateFee - $money;
                $operateFee = 0 > $operateFee ? 0 : $operateFee;
                $wayBill->addOrNewFee(Application_Model_FeeType::OperateFee, $operateFee);
                array_push($types, '操作费');
            }
            if (FALSE !== strpos($zzfyoptions, 'OversizedFee')) {
                $EstimateSum = 'add' == $post['type'] ? $EstimateSum + $money : $EstimateSum - $money;
                $oversizedFee = $wayBill->getFeeByType(Application_Model_FeeType::OperateFee);
                $oversizedFee = 'add' == $post['type'] ? $oversizedFee + $money : $oversizedFee - $money;
                $oversizedFee = 0 > $oversizedFee ? 0 : $oversizedFee;
                $wayBill->addOrNewFee(Application_Model_FeeType::OversizedFee, $oversizedFee);
                array_push($types, '超大费');
            }
            $operate = 'add' == $post['type'] ? 'deduct' : 'recharge';
            $reason = "国际运单{$wayBill->billNo}";
            if ('add' == $post['type']) {
                $reason .= " 增值补交";
            } else {
                $reason .= " 增值退款";
            }
            $reason .= '(' . implode(',', $types) . ')费用';
            $moneyStatus = Application_Model_User::editmoney($wayBill->userId, $money, $reason, '', $operate, $id);
            if (4 == $moneyStatus || 3 == $moneyStatus) {


                $wayBill->addOrNewFee(Application_Model_FeeType::EstimateSum, $EstimateSum);
                $wayBill->save();
                $data = array(
                    'transaction_number' => '',
                    'trader' => $customerTrader,
                    'customer_id' => $wayBill->userId,
                    'member' => Uuch_Util::getUserNikeName(),
                    'amount' => $money,
                    'currency' => 'CNY',
                    'customer_name' => $user->nikename,
                    'rate' => '1',
                    'rate_amount' => '0',
                    'period_start' => $beforeMoney,
                    'period_end' => $periodEnd,
                    'business_type' => $businessType,
                    'order_sn' => $wayBill->billNo,
                    'attribute' => \Zend_Json::encode($attributes),
                    'remark' => '',
                    'created_at' => date('Y-m-d H:i:s')
                );

                try {
                    $api = new General($post['amount'], $account);
                    $api->setFields($data);
                    $api->addTransaction();
                    $api->setFields('trader', $uuchTrader)
                            ->setFields('period_start', $periodEnd)
                            ->setFields('period_end', $periodEnd);
                    $api->addTransaction();
                    $result = array('code' => 'success', 'message' => '');
                } catch (Exception $ex) {
                    $result = array('code' => 'error', 'message' => $ex->getMessage());
                }
            }
        }else{
            $result = array('code' => 'error', 'message' => '对用户账户余额操作失败');
        }
        $this->json($result);
    }
	
	public function pdacheckAction() {
		if ($this->getRequest()->isPost()) {
			$result = 0;
			$brcode = $this->getRequest()->getParam('brcode');
			$billall = Application_Model_wayBillItem::bybillNo($brcode);
			if ($billall) {
				$billall->Interior = 4;
				$billall->save();
				$result = 1;
			} 
			echo $result;
			exit;
		} else {
		  $id = $this->getSafeParam('id');
		  $brcode = $this->getRequest()->getParam('brcode', '');
		  if ($brcode != '') {
			  $billall = Application_Model_wayBillItem::bybillNo($brcode);
			  $query = $brcode;
		  } else if($id != '') {
			  $billall = Application_Model_wayBillItem::load($id);
			  $query = $id;
		  }	else {
				$billall = null;  
				$query = '';
		  }
		  if ($billall) {
			  $this->view->billall = $billall;
		  	  $this->view->storedetail = $billall->getStoreItems();
		      $this->view->storetype = $billall->getItems();			  
		  }
		  $this->view->query = $query;
		  $this->_helper->layout->disableLayout();
		}
	}		

}
